package cn.myzqu.sign.common.miniprogram;


import cn.myzqu.sign.common.miniprogram.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序相关配置
 * @Author: 的川
 * @Date: 2018/12/1.
 */

public class WeChatApp {


    private  String APPID;
    private  String SECRET;
    private  String token;

    /**
     * 获取微信小程序token
     * @return
     */
    public String getToken(){
        return token;
    }

    /**
     * 获取微信用户OpenId
     * @param code 登录凭证
     * @return
     */
    public String getOpenId(String code) {
        String httpUrl = "https://api.weixin.qq.com/sns/jscode2session";
        //封装请求参数
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appid", APPID);
        params.put("secret", SECRET);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        //发送请求
        String result = HttpRequestUtil.get(httpUrl,params);
        JSONObject object = JSONObject.parseObject(result);
        //获取openid
        String openid = object.getString("openid");
        return openid;
    }

    public void setAPPID(String APPID) {
        this.APPID = APPID;
    }

    public void setSECRET(String SECRET) {
        this.SECRET = SECRET;
    }

    /**
     * 刷新token
     */
    public void refreshToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", APPID);
        params.put("secret", SECRET);
        params.put("grant_type", "client_credential");
        String httpResult = HttpRequestUtil.get(url,params);
        JSONObject ob = JSONObject.parseObject(httpResult);
        String token = (String) ob.get("access_token");
        this.token = token;
    }
}
